package com.zzy.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.zzy.common.utils.guanmai.GuanmaiCommon;
import com.zzy.system.domain.PurchaseRefundOrder;
import com.zzy.system.mapper.PurchaseRefundOrderMapper;
import com.zzy.system.service.IPurchaseInStocklOrderDetailitemService;
import com.zzy.system.service.IPurchaseRefundOrderDetailService;
import com.zzy.system.service.IPurchaseRefundOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PurchaseRefundOrderServiceImpl extends ServiceImpl<PurchaseRefundOrderMapper, PurchaseRefundOrder> implements IPurchaseRefundOrderService {
    private static final Logger log = LoggerFactory.getLogger(PurchaseRefundOrderServiceImpl.class);



    @Autowired
    private IPurchaseRefundOrderDetailService iPurchaseRefundOrderDetailService;
    @Autowired
    private IPurchaseInStocklOrderDetailitemService iPurchaseInStocklOrderDetailitemService;
    @Override
    @Transactional
    public String getGuanmaiPurchaseRefundOrderList(Integer status, String startDate, String endDate, Integer offset, Integer limit,Integer searchType) throws IOException {
        List<PurchaseRefundOrder> allPurchaseRefundOrderList = new ArrayList<>();
        while (true) {
            Map<String, Object> paramMap = new HashMap<>();
            // 设置开始日期参数
            paramMap.put("start_date", startDate);
            // 设置截止日期参数
            paramMap.put("end_date", endDate);
            // 设置采购单据状态参数（这里示例设置为已提交状态，值为2，不传会查出全部，可按需不传该参数）
            paramMap.put("status", status);
            // 设置分页offset参数（默认值为0，可按需不传该参数或者修改值）
            paramMap.put("offset", offset);
            // 设置分页limit参数（默认值为100，取值范围<=100，可按需不传该参数或者修改值）
            paramMap.put("limit", limit);

            paramMap.put("search_type", 2);

            //请求观麦 获取订单列表
            String reponse = GuanmaiCommon.sendRequestGet(paramMap,"/v1/api/stock/supplier_refund_sheet/list/1.0" );
            JSONObject reponseJson = JSONObject.parseObject(reponse);
            if (reponseJson.get("code").toString().equals("0")) {
                JSONArray jsonArray = reponseJson.getJSONArray("data");
                if (jsonArray!= null) {
                    // 将当前页的数据解析并添加到总的结果列表中
                    List<PurchaseRefundOrder> purchaseRefundOrders = jsonArray.toJavaList(PurchaseRefundOrder.class);
                    allPurchaseRefundOrderList.addAll(purchaseRefundOrders);
                    // 如果返回的数据条数等于每页显示的数量，说明可能还有更多数据，继续查询下一页
                    if (jsonArray.size() == limit) {
                        offset += limit; // 页码增加，指向下一页
                        continue;
                    } else {
                        // 如果返回的数据条数小于每页显示的数量，说明已经查询完所有数据，结束循环
                        break;
                    }
                }
            } else {
                // 如果接口返回的code不是0，表示请求出现问题，这里可以根据实际情况进行错误处理
                System.out.println("请求出现问题，错误信息：" + reponseJson.get("msg"));
                break;
            }

        }
        int batchSize = 100;
        for (int i = 0; i < allPurchaseRefundOrderList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, allPurchaseRefundOrderList.size());
            List<PurchaseRefundOrder> batchList = allPurchaseRefundOrderList.subList(i, endIndex);
            // 这里可以将batchList用于实际的saveBatch操作或者其他处理
            System.out.println("当前批次数据量: " + batchList.size());

            batchInsertRefundStock(batchList,batchSize);
        }

        System.out.println(allPurchaseRefundOrderList);
        return "";
    }

    //采购入库单插入
    public void batchInsertRefundStock(List<PurchaseRefundOrder> purchaseRefundOrderList, int batchSize) throws JsonProcessingException {
        // 提前查询数据库中已存在的purchase_order_sheetid集合
        List<String> existingSheetIds = getExistingPurchaseRefundOrderSheetIds(purchaseRefundOrderList);
        // 过滤掉已存在的purchase_order_sheetid对应的记录
        List<PurchaseRefundOrder> filteredList = filterExistingRecords(purchaseRefundOrderList, existingSheetIds);
        // 按批次插入过滤后的数据
        for (int i = 0; i < filteredList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, filteredList.size());
            List<PurchaseRefundOrder> batchList = filteredList.subList(i, endIndex);
            System.out.println("当前批次数据量: " + batchList.size());
            this.saveBatch(batchList);
            for(PurchaseRefundOrder purchaseRefundOrder:batchList){
                //循环查询采购入库单的详情
                getGauanMaiOrderDetail(purchaseRefundOrder.getSupplierRefundSheetId());
            }
        }
    }
    private List<String> getExistingPurchaseRefundOrderSheetIds(List<PurchaseRefundOrder> purchaseRefundOrders) {
        if (purchaseRefundOrders == null || purchaseRefundOrders.isEmpty()) {
            return new ArrayList<>();
        }

        List<String> sheetIdList = new ArrayList<>();
        for (PurchaseRefundOrder purchaseRefundOrder : purchaseRefundOrders) {
            sheetIdList.add(purchaseRefundOrder.getSupplierRefundSheetId());
        }

        QueryWrapper<PurchaseRefundOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("supplier_refund_sheet_id").in("supplier_refund_sheet_id", sheetIdList);

        return this.getBaseMapper().selectObjs(queryWrapper).stream()
                .map(obj -> (String) obj).collect(Collectors.toList());
    }

    private List<PurchaseRefundOrder> filterExistingRecords(List<PurchaseRefundOrder> purchaseRefundOrders, List<String> existingSheetIds) {
        List<PurchaseRefundOrder> filteredList = new ArrayList<>();
        for (PurchaseRefundOrder order : purchaseRefundOrders) {
            if (!existingSheetIds.contains(order.getSupplierRefundSheetId())) {
                filteredList.add(order);
            }
        }
        return filteredList;
    }





    public void getGauanMaiOrderDetail(String refundSheetId) throws JsonProcessingException {
        Map<String, Object> paramMap=new HashMap<>();
        // 设置开始日期参数
        paramMap.put("supplier_refund_sheet_id", refundSheetId);
        //请求观麦 获取订单列表
        String reponse = GuanmaiCommon.sendRequestGet(paramMap,"/v1/api/stock/supplier_refund_sheet/get/1.0" );
        JSONObject reponseJson = JSONObject.parseObject(reponse);
        if (reponseJson!=null&&reponseJson.get("code").toString().equals("0")) {
            JSONObject jsonObject = reponseJson.getJSONObject("data");
            PurchaseRefundOrder purchaseRefundOrder = JSON.parseObject(jsonObject.toString(), PurchaseRefundOrder.class);
            if(purchaseRefundOrder.getSupplierRefundSheetId()!=null){
                // 使用forEach方法遍历Details集合并设置purchaseSheetId属性
                purchaseRefundOrder.getDetails().forEach(detail -> detail.setSupplierRefundSheetId(refundSheetId));
                iPurchaseRefundOrderDetailService.saveRefundOrderDetail(purchaseRefundOrder.getDetails());
            }

        }
    }


}